package com.qlhx.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qlhx.common.model.MQRegFace;
import com.qlhx.common.model.Result;
import com.qlhx.common.util.IConfig;
import com.qlhx.model.BaseAccessRecord;
import com.qlhx.model.BaseMember;
import com.qlhx.mq.MQSender;
import com.qlhx.service.AccessRecordService;
import com.qlhx.service.MemberService;
import com.qlhx.service.VisitorReasonsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "访客机接口", description = "访客机接口")
@CrossOrigin(maxAge = 3600)
@RestController
@Scope(value = "prototype")
@RequestMapping("fkterminal")
public class TerminalController {

	private final Logger logger = LoggerFactory.getLogger(TerminalController.class);

	@Autowired
	AccessRecordService accessRecordService;

	@Autowired
	MemberService memberService;

	@Autowired
	VisitorReasonsService visitorReasonsService;

	@Autowired
	private MQSender sender;
	
	@ApiOperation(value = "根据手机号码后4位或姓名首字母查询被访人", notes = "根据手机号码后4位或姓名首字母查询被访人（不区分大小写）")
	@RequestMapping(value = "/findUserByPhoneOrName/{param}/{pageindex}/{pagesize}", method = RequestMethod.GET, produces = {
			"application/json", "application/xml" })
	public @ResponseBody Result<List<BaseMember>> findUserByPhoneOrName(
			@ApiParam("手机后4位或姓名首字母（不区分大小写）") @PathVariable String param,
			@ApiParam("页码") @PathVariable Integer pageindex, @ApiParam("显示数量") @PathVariable Integer pagesize)
			throws Exception {
		Result<List<BaseMember>> result = new Result<List<BaseMember>>();
		try {
			if (param != null && !"".equals(param) && !"{param}".equals(param)) {
				Double pagecount = Math
						.ceil(memberService.findUserCountByPhoneOrName(param.toLowerCase()) / (double) pagesize);
				result.setPagecount(pagecount.intValue());
				List<BaseMember> listUser = memberService.findUserByPhoneOrName(param.toLowerCase(), pageindex,
						pagesize);
				result.setContent(listUser);
			} else {
				result.setCode(1001);
				result.setMsg("参数错误！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(5000);
			result.setMsg("服务端异常！");
			throw e;
		} 
			return result;
		
	}

	@ApiOperation(value = "访客登记接口", notes = "记录访客登记信息", response = Result.class)
	@Transactional
	@RequestMapping(value = "/saveVisitorInfo", method = RequestMethod.POST, produces = { "application/json",
			"application/xml" }, consumes = { "application/json", "application/xml" })
	public @ResponseBody Result<Map<String, Object>> saveVisitorInfo(
			@ApiParam("来访记录对象") @RequestBody BaseAccessRecord record) throws Exception {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		try {
			record.setCreatetime(new Date());
			result = accessRecordService.SaveAccessRecord(record);
			MQRegFace mQRegFace = new MQRegFace(null, record.getVisitor().getName(), record.getCardnum(),
					record.getSitephoto());
			sender.regFace(mQRegFace);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 手动回滚事物
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setCode(5000);
			result.setMsg("登记失败" + e.getMessage());
			logger.error("访客登记失败", e);
		}
		return result;
	}

	@ApiOperation(value = "添加随行人员", notes = "添加随行人员")
	@Transactional
	@RequestMapping(value = "/addEntourage", method = RequestMethod.POST, produces = { "application/json",
			"application/xml" }, consumes = { "application/json", "application/xml" })
	public @ResponseBody Result<Map<String, Object>> addEntourage(
			@ApiParam("来访记录对象") @RequestBody BaseAccessRecord record) throws Exception {
		Result<Map<String, Object>> result = new Result<Map<String, Object>>();
		try {
			result = accessRecordService.addEntourage(record);
			MQRegFace mQRegFace = new MQRegFace(null, record.getVisitor().getName(), record.getCardnum(),
					record.getSitephoto());
			sender.regFace(mQRegFace);
		} catch (Exception e) {
			e.printStackTrace();
			// 手动回滚事物
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.setCode(5000);
			result.setMsg("服务端异常！");
		}
		return result;
	}

	@ApiOperation(value = "来访事由列表", notes = "获取来访事由列表")
	@RequestMapping(value = "/findReasons", method = RequestMethod.GET, produces = { "application/json",
			"application/xml" })
	public @ResponseBody Result findReasons() {
		Result result = new Result();
		try {
			// 获取来访事由列表
			result.setContent(visitorReasonsService.list());
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(5000);
			result.setMsg("服务端异常！");
		}
		return result;

	}
	
	 @ApiOperation(value = "来访记录查询", notes = "来访记录查询")
	    @Transactional
	    @RequestMapping(value = "/findAccessRecord", method = RequestMethod.POST, produces = {
	            "application/json", "application/xml"}, consumes = {
	            "application/json", "application/xml"})
	    public
	    @ResponseBody
	    Result<List<BaseAccessRecord>> findAccessRecord(
	            @ApiParam("来访记录对象") @RequestBody BaseAccessRecord record)
	            throws Exception {
	        Result<List<BaseAccessRecord>> result = new Result<List<BaseAccessRecord>>();
	        try {
	            if (record.getPageNum() == null || record.getPageNum() <= 0) {
	                record.setPageNum(1);
	            }
	            if (record.getNum() == null || record.getNum() <= 0) {
	                record.setNum(10);
	            }

	            // 获取总页数
	            int pageCount = (int) Math.ceil(accessRecordService
	                    .findAccessRecordPageCount(record) / 10d);

	            result.setPagecount(pageCount);

	            result.setPageNum(record.getPageNum());

	            // 获取指定页数的数据
	            result.setContent(accessRecordService.findAccessRecord(record));

	        } catch (Exception e) {
	            e.printStackTrace();
	            result.setCode(5000);
	            result.setMsg("服务端异常！");
	            throw e;
	        } finally {
	            return result;
	        }
	    }
	 
	 @ApiOperation(value = "根据卡号查询有效的访客记录", notes = "根据卡号查询有效的访客记录")
	    @RequestMapping(value = "/findAccessRecordByCardNum/{cardNum}", method = RequestMethod.GET, produces = {
	            "application/json", "application/xml"})
	    public
	    @ResponseBody
	    Result<BaseAccessRecord> findAccessRecordByCardNum(
	            @ApiParam("卡号") @PathVariable String cardNum)
	            throws Exception {
	        Result<BaseAccessRecord> result = new Result<BaseAccessRecord>();
	        try {
	        	BaseAccessRecord ar = accessRecordService.findAccessRecordByCardNum(cardNum);
	        	if(ar != null)
	        	{
	        		result.setContent(ar);
	        	}
	        	else
	        	{
	        		result.setCode(1001);
	                result.setMsg("没有找到有效的访客记录");
	        	}
	            
	        } catch (Exception e) {
	            e.printStackTrace();
	            result.setCode(5000);
	            result.setMsg("服务端异常！");
	            throw e;
	        } finally {
	            return result;
	        }
	    }

}
